const mongoose = require('mongoose');

// 拟授课方向选项
const teachingDirections = [
  '导论',
  '新时代坚持和发展中国特色社会主义',
  '以中国式现代化全面推进中华民族伟大复兴',
  '坚持党的全面领导',
  '坚持以人民为中心',
  '全面深化改革开放',
  '推动高质量发展',
  '社会主义现代化建设的教育、科技、人才战略',
  '发展全过程人民民主',
  '全面依法治国',
  '建设社会主义文化强国',
  '以保障和改善民生为重点加强社会建设',
  '建设社会主义生态文明',
  '维护和塑造国家安全',
  '建设巩固国防和强大人民军队',
  '坚持"一国两制"和推进祖国完全统一',
  '中国特色大国外交和推动构建人类命运共同体',
  '全面从严治党'
];

const cadreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '姓名为必填项'],
    trim: true
  },
  gender: {
    type: String,
    required: [true, '性别为必填项'],
    enum: ['男', '女', '其他']
  },
  birthDate: {
    type: Date,
    required: [true, '出生年月为必填项']
  },
  nativePlace: {
    type: String,
    trim: true
  },
  level: {
    type: String,
    enum: ['省级', '厅局级', '县处级', '乡科级', '其他']
  },
  position: {
    type: String,
    trim: true
  },
  cadreType: {
    type: String,
    enum: ['厅局级干部', '中管干部']
  },
  unitId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Unit',
    required: [true, '所属单位为必填项']
  },
  highestEducation: {
    type: String,
    enum: ['博士研究生', '硕士研究生', '本科', '大专', '高中', '其他']
  },
  highestDegree: {
    type: String,
    enum: ['博士', '硕士', '学士', '无']
  },
  expertise: {
    type: String,
    trim: true
  },
  proposedTeachingDirections: {
    type: [String],
    validate: {
      validator: function(v) {
        return v.length <= 2 && v.every(direction => teachingDirections.includes(direction));
      },
      message: '拟授课方向最多选择2个，且必须从预定义选项中选择'
    },
    required: [true, '拟授课方向为必填项']
  },
  intendedUniversity1: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'University',
    required: [true, '意向授课高校1为必填项']
  },
  intendedUniversity2: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'University'
  },
  intendedUniversity3: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'University'
  },
  personnelChanges: {
    type: String,
    trim: true
  },
  remarks: {
    type: String,
    trim: true
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 虚拟字段：年龄
cadreSchema.virtual('age').get(function() {
  if (!this.birthDate) return null;
  const today = new Date();
  const birthDate = new Date(this.birthDate);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
});

// 索引
cadreSchema.index({ name: 1 });
cadreSchema.index({ unitId: 1 });
cadreSchema.index({ proposedTeachingDirections: 1 });

module.exports = mongoose.model('Cadre', cadreSchema);
